package leetcode.doublepointer;

import java.util.Arrays;

//581. 最短无序连续子数组
public class FindUnsortedSubarray {
    public static void main(String[] args) {
            int[] data = {2,6,4,8,10,9,15};
        System.out.println(findUnsortedSubarray2(data));
    }
    public static int findUnsortedSubarray(int[] nums) {
        int[] temp = nums.clone();
        Arrays.sort(temp);
        int p = 0;
        int q = temp.length-1;
        while (p<nums.length-1){
            if (temp[p]!=nums[p]){
                break;
            }else {
                p++;
            }

        }
        while (q>0){
            if (temp[q]!=nums[q]){
                break;
            }else {
                q--;
            }
        }
        if (p-q+1==nums.length){
            return 0;
        }else {
            return q-p+1;
        }
    }

    public static int findUnsortedSubarray2(int[] nums) {
        int[] tmp = new int[nums.length];
        System.arraycopy(nums,0,tmp,0,nums.length);
        Arrays.sort(tmp);
        int p=0;
        int q = nums.length-1;
        while (p<=q &&nums[p]==tmp[p]){
         p++;
        }
        while (p<=q &&nums[q]==tmp[q] ){
            q--;
        }
        return q-p+1;
    }
}
